package thesis.prototype;

import java.util.ArrayList;

import thesis.prototype.objects.Contact;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class MembersActivity extends Activity implements OnClickListener {

	// Constants
	//private final int ADD_NEWNUMBER_INTENT = 20;
	//private final int ORGANIZE_DETAILS_INTENT = 21;
	
	// Buttons
	private Button b_mem_next;
	private Button b_mem_addnumber;
	private Button b_mem_cancel;
	
	// ListView
	private ListView l_contacts;
	private ListAdapter l_listadapter;
	
	// ArrayLists, for contacts list
	//private ArrayList<String> arr_names;
	//private ArrayList<String> arr_numbers;
	private ArrayList<Contact> arr_contacts;
	//private String[] members;
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.organize_members);
		
		b_mem_next = (Button) findViewById(R.id.organizem_next);
		b_mem_addnumber = (Button) findViewById(R.id.organizem_addnumber);
		b_mem_cancel = (Button) findViewById(R.id.organizem_cancel);
		//l_contacts = (ListView) findViewById(R.id.memberlist);
		
        //arr_names = new ArrayList<String>();
        //arr_numbers = new ArrayList<String>();
        arr_contacts = new ArrayList<Contact>();
		
		addButtonListeners();
		populateContactsArray();
		refreshContactsList();
	}
	
	private void addButtonListeners()
	{
		if (b_mem_next != null) b_mem_next.setOnClickListener(this);
		if (b_mem_cancel != null) b_mem_cancel.setOnClickListener(this);
		if (b_mem_addnumber != null) b_mem_addnumber.setOnClickListener(this);
	}
	
	private void populateContactsArray()
	{	
		// Getting contacts from phone!
		ContentResolver cr = getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
				null, null, null, null);
		if(cur.getCount() > 0)
		{
			while (cur.moveToNext())
			{
				String id = cur.getString(
						cur.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cur.getString(
						cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (Integer.parseInt(cur.getString(cur.getColumnIndex(
						ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0 )
				{
					// QUERY PHONE HERE
					Cursor pCur = cr.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
							new String[] {id}, null);
					while (pCur.moveToNext()) {
						// Do something with phones
						String number = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
						int type = pCur.getInt(pCur.getColumnIndex(Phone.TYPE));
						switch (type) {
						case Phone.TYPE_MOBILE:
						case Phone.TYPE_WORK_MOBILE:
							//arr_names.add(name);
							String temp_number = number.replaceAll("-", "");
							//arr_numbers.add(temp_number);
							arr_contacts.add(new Contact(name, temp_number));
							break;
						default:
							break;
						}
					}
					pCur.close();
				}
			}
		}
		cur.close();
	}
	
	@SuppressWarnings("unchecked")
	private void refreshContactsList()
	{
    	/*members = new String[arr_names.size()];
        for(int i=0;i<arr_names.size();i++)
        {
        	members[i] = arr_names.get(i)+ "\n(" + arr_numbers.get(i) + ")";
        }*/
        
        if (l_contacts == null) 
        {
    		l_contacts = (ListView) findViewById(R.id.memberlist);
    		l_listadapter = new ArrayAdapter<Contact>(this, android.R.layout.simple_list_item_multiple_choice, arr_contacts);
        	l_contacts.setAdapter(l_listadapter);
        	l_contacts.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        	l_contacts.setOnItemClickListener(new OnItemClickListener()
        	{
        	    public void onItemClick(AdapterView<?> parent, View view,
        	    		int position, long id)
        	    {
        	    	if(((CheckedTextView) view).isChecked())
        	    		((CheckedTextView) view).setChecked(false);
        	    	else
        	    		((CheckedTextView) view).setSelected(true);
        	    }
        	});
        }
        else
        {
        	((ArrayAdapter<Contact>)(l_contacts.getAdapter())).notifyDataSetChanged();
        	l_contacts.invalidate();
        }
	}
	
	@Override
	public void onClick(View v)
	{
		if(v==b_mem_cancel)
		{
			setResult(RESULT_CANCELED);
			finish();
		}
		else if(v==b_mem_addnumber)
		{
			Intent intent = new Intent(this, thesis.prototype.AddNumberDialog.class);
			startActivityForResult(intent, HelloActivity.ADD_NEWNUMBER_INTENT);
		}
		else if(v==b_mem_next)
		{
			// Getting checked contacts
			ArrayList<Contact> arr_invited = new ArrayList<Contact>();
			SparseBooleanArray contacts = l_contacts.getCheckedItemPositions();
			//ArrayList<String> invited_names = new ArrayList<String>();
			//ArrayList<String> invited_numbers = new ArrayList<String>();
			int size = contacts.size();
			for(int i=0;i<size;i++)
			{
				if(contacts.get(contacts.keyAt(i))==true)
				{
					arr_invited.add(arr_contacts.get(contacts.keyAt(i)));
					//invited_names.add(arr_names.get(i));
					//invited_numbers.add(arr_numbers.get(i));
				}
			}
			
			if(arr_invited.isEmpty())
			{
				Toast t = Toast.makeText(this, "Invite at least one contact!", Toast.LENGTH_LONG);
				t.show();
			}
			else
			{
				HelloActivity.arr_invited = arr_invited;
				//i.putExtra("thesis.prototype.MembersActivity.contacts_names", arr_names);
				//i.putExtra("thesis.prototype.MembersActivity.contacts_numbers", arr_numbers);
				//i.putExtra("thesis.prototype.MembersActivity.invited", arr_invited);
				//setResult(RESULT_OK, i);
				//finish();

				Intent i = new Intent(this, DetailsActivity.class);
				startActivityForResult(i, HelloActivity.ORGANIZE_DETAILS_INTENT);
			}
		}
	}
	
	private void addNewContact(String newName, String newNumber)
	{
		//arr_names.add(newName);
		//arr_numbers.add(newNumber);
		
		arr_contacts.add(new Contact(newName, newNumber));
		
		refreshContactsList();
	}

	@Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data) {     
		super.onActivityResult(requestCode, resultCode, data); 
		switch(requestCode) { 
		case (HelloActivity.ADD_NEWNUMBER_INTENT) :
			if (resultCode == Activity.RESULT_OK) {
				String new_num = data.getExtras().getString("thesis.prototype.AddNumberDialog.NEW_CONTACT");
				addNewContact("[New Contact]", new_num);
			}
			else if (resultCode == Activity.RESULT_CANCELED) // cancelled Adding new number, do nothing
			{
			}
			break; 
		case (HelloActivity.ORGANIZE_DETAILS_INTENT):
			if (resultCode == Activity.RESULT_OK) // finished with everything
			{
				setResult(RESULT_OK);
				finish();
			}
			else if (resultCode == Activity.RESULT_CANCELED) // cancelled from Details
			{
				// RESULT CANCELLED, clean up all data and exit
				HelloActivity.arr_invited = null;
				HelloActivity.meet_title="";
				HelloActivity.meet_time="";
				HelloActivity.meet_date="";
				setResult(RESULT_CANCELED);
				finish();
			}
			else if (resultCode == Activity.RESULT_FIRST_USER) // pressed previous on Details
			{
				// nothing should happen
			}
			break; 
		}
	}
}
